---
import BaseLayout from "../../layouts/BaseLayout.astro";
import BlogPost from "../../components/BlogPost.astro";

export async function getStaticPaths() {
  const allPosts = Object.values(
    import.meta.glob("../posts/*.md", { eager: true }),
  );

  // 安全地收集所有标签
  const allTags = new Set();

  allPosts.forEach((post: any) => {
    // 检查 frontmatter 和 tags 是否存在，并且 tags 是数组
    if (post.frontmatter?.tags && Array.isArray(post.frontmatter.tags)) {
      post.frontmatter.tags.forEach((tag: string) => {
        if (tag) allTags.add(tag);
      });
    }
  });

  return Array.from(allTags).map((tag) => {
    return {
      params: { tag },
      props: {
        posts: allPosts.filter((post: any) =>
          post.frontmatter?.tags?.includes?.(tag),
        ),
      },
    };
  });
}

const { tag } = Astro.params;
const { posts } = Astro.props;
---

<BaseLayout pageTitle={tag}>
  <p>包含「{tag}」标签的文章</p>
  <ul>
    {
      posts.map((post: any) => (
        <BlogPost url={post.url} title={post.frontmatter.title} />
      ))
    }
  </ul>
</BaseLayout>
